package com.itqf.controller;

import com.itqf.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter(Constants.TAG);
        resp.setContentType("text/html;charset = UTF-8");
        resp.setHeader("Content-Type","text/html;charset = UTF-8");
        //跳转首页，标识符异常处理
        if(methodStr==null&&methodStr.equals("")){
            methodStr = Constants.INDEX;
        }
        //反射获取方法
        Class clazz =  this.getClass();
        try {
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            Object result = method.invoke(this,req,resp);
            if(result !=null){
                String str = (String)result;
                if(str.startsWith(Constants.FOW)) {
                   String path = str.substring(str.indexOf(Constants.FLAG)+1);
                    req.getRequestDispatcher(path).forward(req, resp);
                }else if(str.startsWith(Constants.REDIRECT)) {
                    String path = str.substring(str.indexOf(Constants.FLAG)+1);
                    resp.sendRedirect(path);
                }else{
                    resp.getWriter().println(str);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public String index(HttpServletRequest req, HttpServletResponse resp) throws IOException{
       return Constants.FOW+"/index.jsp";
    }
}
